/**
 *  学习目标：Todos 案例
 */
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
// import { useSelector } from 'react-redux';
import { useAppSelector } from './store';
import {
  addTask,
  AllCheckReducer,
  changeType,
  checkById,
  clearCompleted,
  todoDel,
} from './store/action/todo';
import './styles/base.css';
import './styles/index.css';

export default function App() {
  return (
    <section className="todoapp">
      {/* 头部 */}
      <Header></Header>
      {/* 主体 */}
      <Main></Main>
      {/* 底部 */}
      <Footer></Footer>
    </section>
  );
}
function Footer() {
  const { type, list } = useAppSelector((state) => state.todo);
  const activeLength = list.filter((item) => !item.isDone).length;
  const dispatch = useDispatch();
  return (
    <footer className="footer">
      <span className="todo-count">
        <strong>{activeLength}</strong> 剩余
      </span>
      <ul className="filters">
        <li>
          <a
            className={type === 'all' ? 'selected' : ''}
            href="#/"
            onClick={() => dispatch(changeType('all'))}
          >
            全部
          </a>
        </li>
        <li>
          <a
            className={type === 'active' ? 'selected' : ''}
            href="#/active"
            onClick={() => dispatch(changeType('active'))}
          >
            未完成
          </a>
        </li>
        <li>
          <a
            className={type === 'completed' ? 'selected' : ''}
            href="#/completed"
            onClick={() => dispatch(changeType('completed'))}
          >
            已完成
          </a>
        </li>
      </ul>
      <button
        className="clear-completed"
        onClick={() => dispatch(clearCompleted())}
      >
        清除已完成
      </button>
    </footer>
  );
}

function Main() {
  // const state = useSelector((state: RootState) => state);
  const { list, type } = useAppSelector((state) => state.todo);
  const newList = list.filter((item) => {
    if (type === 'active') return !item.isDone;
    if (type === 'completed') return item.isDone;
    return true;
  });
  const isCheck =
    (list.length && list.every((item) => item.isDone === true)) || false;
  const dispatch = useDispatch();
  useEffect(() => {
    localStorage.setItem('todo-list', JSON.stringify(list));
    localStorage.setItem('todo-type', type);
  }, [list, type]);
  return (
    <section className="main">
      <input
        id="toggle-all"
        className="toggle-all"
        type="checkbox"
        checked={isCheck}
        onChange={(e) => dispatch(AllCheckReducer(e.target.checked))}
      />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {newList.map((item) => {
          return (
            <li className={item.isDone ? 'completed' : ''} key={item.id}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.isDone}
                  onChange={() => dispatch(checkById(item.id))}
                />
                <label>{item.task}</label>
                <button
                  className="destroy"
                  onClick={() => dispatch(todoDel(item.id))}
                ></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}

function Header() {
  const [task, setTask] = useState('');
  const dispatch = useDispatch();
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    switch (e.key) {
      case 'Enter':
        if (task.trim() === '') return alert('不能为空');
        dispatch(addTask(task));
        break;
      case 'Escape':
        setTask('');
        break;
      default:
        break;
    }
  };
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
        value={task}
        onChange={(e) => setTask(e.target.value)}
        onKeyDown={handleKeyDown}
      />
    </header>
  );
}
